package com.crm.controller.quotController;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.crm.beans.NewQuotVO;
import com.crm.dao.AttachmentHistoryDAO;
import com.crm.dao.ClientdetDAO;
import com.crm.dao.CurrencyDAO;
import com.crm.dao.ExecutivesDAO;
import com.crm.dao.OpportunityDAO;
import com.crm.dao.PartsDAO;
import com.crm.dao.QuotPartsDAO;
import com.crm.dao.QuotationDAO;
import com.crm.dao.SourceInfoDAO;
import com.crm.dao.SourcesDAO;
import com.crm.dao.SupplierDAO;
import com.crm.dao.VariablesDAO;
import com.crm.entity.AttachmentHistory;
import com.crm.entity.Business;
import com.crm.entity.Clientdet;
import com.crm.entity.Currency;
import com.crm.entity.Executives;
import com.crm.entity.Opportunity;
import com.crm.entity.Parts;
import com.crm.entity.QuotParts;
import com.crm.entity.Quotation;
import com.crm.entity.SourceInfo;
import com.crm.entity.Sourcecompare;
import com.crm.entity.User;
import com.crm.entity.Variables;
import com.crm.util.Constants;
import com.crm.util.NumToWords;

@Controller
@RequestMapping("/newquot")
public class NewQuotController {
	protected final Log logger = LogFactory.getLog(getClass());

	@RequestMapping("/show.do")
	public ModelAndView show(HttpServletRequest req, HttpSession session,
			ModelAndView model) throws Exception {
		Business bus = (Business) session.getAttribute("business");

		if (bus == null)
			return new ModelAndView("/jsp/index.jsp");
		String tAndC = bus.getTandc();
		String status = Constants.ST_SOURCES_COMPARED;
		//OpportunityDAO oprD = new OpportunityDAO();

		List<Opportunity> opr = null;
		try {
			opr = (List<Opportunity>) OpportunityDAO.getSingleInstance().getEnqByStatus(bus.getBusinessId(),
					status);
			logger.info("opportunity list is " + opr);
		} catch (NullPointerException e) {
			e.printStackTrace();
		}

		model = new ModelAndView("/jsp/NewQuotation.jsp")
				.addObject("opprtunity", opr).addObject("submenu", "quotation")
				.addObject("menuName", "quotation").addObject("terms", tAndC);
		return model;
	}

	@RequestMapping("/quotsave.do")
	public ModelAndView quotsave(HttpSession session,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		session = request.getSession();
		User user = (User) session.getAttribute("user");
		Business bus = (Business) session.getAttribute("business");
		if (bus == null)return new ModelAndView("/jsp/index.jsp");
		String quotNo = request.getParameter("quotno");
		String terms = request.getParameter("termsAndConditions");
		String refno = request.getParameter("reflist");
		logger.info("the reference number is" + refno);
		//OpportunityDAO oprDAO = new OpportunityDAO();

		Opportunity op = OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(), refno);
		int rid = op.getId();
		Quotation quotObj = new Quotation();
		Set<QuotParts> sqp = new HashSet<QuotParts>();
		List<com.crm.beans.QuotParts> lquot = new ArrayList<com.crm.beans.QuotParts>();
		String rcount = request.getParameter("rowcount");
		int rowcount = Integer.parseInt(rcount);
		logger.info("row count " + rowcount);
		double totalPrice = 0;
		for (int i = 1; i <= rowcount; i++) {
			String partNum = request.getParameter("partno" + i);
			String partId = request.getParameter("partid" + i);
			int prtid = Integer.parseInt(partId);
			logger.info("part number " + partNum);
			PartsDAO partDAO = new PartsDAO();
			Parts partobj = partDAO.getById(rid, prtid, bus.getBusinessId());
			String make = request.getParameter("make" + i);
			String desc = request.getParameter("desc" + i);
			String required = request.getParameter("required" + i);
			int rQty = Integer.parseInt(required.trim());
			String source = request.getParameter("source" + i);
			String supplier = request.getParameter("supplier" + i);

			String fright = request.getParameter("fright" + i);
			float fri = Float.parseFloat(fright.trim());
			String assesable = request.getParameter("assesable" + i);
			float asses = Float.parseFloat(assesable.trim());
			float bcdVal = Float.parseFloat(rcount);
			String stot = request.getParameter("stot" + i);
			float subtotal = Float.parseFloat(stot.trim());

			String margin = request.getParameter("margin" + i);
			float mar = Float.parseFloat(margin.trim());
			String unitprice = request.getParameter("unitprice" + i);
			float up = Float.parseFloat(unitprice.trim());
			logger.info("the unitprice value is" + unitprice);
			String quotprice = request.getParameter("quotprice" + i);
			float qprice = Float.parseFloat(quotprice.trim());

			totalPrice = totalPrice + qprice;
			String delivery = request.getParameter("delivery" + i);

			SourcesDAO soDAO = new SourcesDAO();
			int sid = soDAO.getByName(source, bus.getBusinessId()).getId();
			SupplierDAO supDAO = new SupplierDAO();
			int supid = supDAO.getByName(supplier, bus.getBusinessId()).getId();

			int moq = 0;
			QuotParts Qparts = new QuotParts(bus, quotObj.getId(), qprice, fri,
					asses, up, rQty, partobj, delivery, make, moq, bcdVal, mar,
					supid, sid, subtotal);
			com.crm.beans.QuotParts qparts = new com.crm.beans.QuotParts(
					partNum, required, unitprice, make, "", "", delivery, ""
							+ i, desc, quotprice);

			sqp.add(Qparts);
			lquot.add(qparts);
		}// end of For loop
		quotObj.setEnqid(op);
		quotObj.setBusinessId(bus);

		ClientdetDAO cliDAO = new ClientdetDAO();
		String orgname = op.getOrganisation();
		Clientdet cli = cliDAO.getCliOrg(bus.getBusinessId(), orgname);

		quotObj.setClientid(cli);
		
		quotObj.setOrdrby(op.getBusinessId().getBusinessName());

		String addr = bus.getBusinessName() + "/n" + bus.getAddress();
		String qutid = request.getParameter("quotno");
		quotObj.setQuotno(qutid);

		


		java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
		String d = date.toString();
		quotObj.setQutdate(d);
		QuotationDAO qDAO = new QuotationDAO();
		quotObj.setQuotParts(sqp);
		
		final Map<String, String> parms = new HashMap<String, String>();
		parms.put("quoteNo", quotNo);

		String url = session.getServletContext().getContextPath();
		logger.info("url of contextpath" + url);
		
		int priceint = (int) totalPrice;
		quotObj.setQuotvalue(totalPrice);
		NumToWords numto = new NumToWords();
		String priceword = numto.convert(priceint);
		logger.info("total price in words is" + priceword);
		String quotCurrency="U/P";
		if(op.getCurencytype().equals(Constants.ST_CUR_DOLLAR)){
			quotCurrency="U/P(In $)";
		}
		else if(op.getCurencytype().equals(Constants.ST_CUR_EURO)){
			quotCurrency="U/P(In EUROs)";
		}
		else if(op.getCurencytype().equals(Constants.ST_CUR_YEN)){
			quotCurrency="U/P(In YENs)";
		}
		else if(op.getCurencytype().equals(Constants.ST_CUR_RUPEE)){
			quotCurrency="U/P(In Rs.)";
		}
		else if(op.getCurencytype().equals(Constants.ST_CUR_POUND)){
			quotCurrency="U/P(In POUNDs)";
		}
		else if(!op.getCurencytype().equals(null)){
			quotCurrency="U/P(In "+op.getCurencytype()+")";
		}
		parms.put("quotCurrency",quotCurrency);
		parms.put("priceword", "Total(" + op.getCurencytype() + "   "
				+ priceword + " Only )");
		parms.put("customer",  cli.getAddr() + ".\n");
		parms.put("from", op.getBusinessId().getBusinessName());
		parms.put("enqNo", op.getEnqnum());
		parms.put("refNo", op.getRefNum());
		String date2 = Constants.IST_DATE_FORMATER.format(new Date());
		parms.put("date", date2);
		parms.put("total", priceint + "");
		parms.put("CompanyAddress", op.getBusinessId().getBusinessName() + "\n"
				+ addr);
		parms.put("terms", terms);
		parms.put("quotid", quotNo);
		parms.put("footer",
				"Looking forward for your valuable purchase order at the earliest"
						+ "\n\n"
						+ "Thanking you & assuring our best services at all the times."
						+ "\n\n" + "for " + bus.getBusinessName() + "\n\n" + ""
						+ user.getFirstName() + " " + user.getLastName()
						+ "\n\n" + "Manager Operations");
		String opuser = op.getOrganisation();
		if (op.getUser() != null && op.getUser() != "Please Select") {
			opuser = op.getUser();
		}
		parms.put("subject", "Kind Attention Mr/Mrs. " + opuser);
		//getting jasper from the application path
		JasperReport report = (JasperReport) JRLoader.loadObject(session
				.getServletContext().getResourceAsStream(
						"/WEB-INF/classes/reports/newquot.jasper"));
		JasperPrint prt = JasperFillManager.fillReport(report, parms,
				new JRBeanArrayDataSource(lquot.toArray()));
		byte[] pdfReport = JasperExportManager.exportReportToPdf(prt);
		// this is for exporting jasper as msword format.
		JRDocxExporter docExporter=new JRDocxExporter();
		ByteArrayOutputStream docStream=new ByteArrayOutputStream();
		docExporter.setParameter(JRDocxExporterParameter.JASPER_PRINT,prt);
		docExporter.setParameter(JRDocxExporterParameter.OUTPUT_STREAM,docStream);
		docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
		docExporter.exportReport();
		pdfReport = docStream.toByteArray();

		boolean tb = op.getTechnicalbid();
		if (tb) {
			try {
				JasperReport techreport = (JasperReport) JRLoader
						.loadObject(session
								.getServletContext()
								.getResourceAsStream(
										"/WEB-INF/classes/reports/newtechquot.jasper"));

				JasperPrint print = JasperFillManager.fillReport(techreport,
						parms, new JRBeanArrayDataSource(lquot.toArray()));
				byte[] pdfRep = JasperExportManager.exportReportToPdf(print);
				
				docExporter.setParameter(JRDocxExporterParameter.JASPER_PRINT,print);
				docExporter.setParameter(JRDocxExporterParameter.OUTPUT_STREAM,docStream);
				docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
				docExporter.exportReport();
				pdfRep = docStream.toByteArray();
				
				AttachmentHistory attachment = new AttachmentHistory(
						"application/msword", bus, Constants.TECHNICAL_QUOTATION, pdfRep,
						op.getRefNum(), quotNo, new java.util.Date());
				AttachmentHistoryDAO atDAO = new AttachmentHistoryDAO();
				try {
					atDAO.insert(attachment);
				} catch (Exception e) {
					e.printStackTrace();
				}

				logger.info("the length of pdf is" + pdfRep.length);
				logger.info("the length of pdf is" + pdfRep.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		int busid = bus.getBusinessId();
		
		
		
		// saving quotation pdf in database
		logger.info("the bus object is" + bus);
		logger.info("the bus object is" + bus.getBusinessId());

		AttachmentHistory attach = new AttachmentHistory("application/msword",
				bus,Constants.QUOTATION, pdfReport, op.getRefNum(), quotNo,
				new java.util.Date());
		AttachmentHistoryDAO atDAO = new AttachmentHistoryDAO();
		try{
			qDAO.insert(quotObj);
			String status = Constants.ST_GENERATED_QUOTATION;
			OpportunityDAO.getSingleInstance().updateStatus(busid, status, rid);
			atDAO.insert(attach);
			System.out.println("Quotation Has Generated Successfully.");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("Failed To Create Quotation.");
		}

		logger.info("the length of pdf is" + pdfReport.length);
		logger.info("the length of pdf is" + pdfReport.toString());
		// technical bid is there or not

		ModelAndView model = new ModelAndView("/jsp/Quotation.jsp");
		model.addObject("genQuotNo", quotNo);
		if (tb) {
			model.addObject("techbidno", quotNo);
		}

		model.addObject("resmsg",
				"Sucesssfully Created Quotation With Quotation Number" + quotNo);
		model.addObject("submenu", "quotation");
		model.addObject("menuName", "quotation");
		return model;

	}

	@RequestMapping("/getquot.do")
	public ModelAndView getQuot(HttpServletRequest request,
			HttpSession session, ModelAndView model) throws Exception {
		Business bus = (Business) session.getAttribute("business");
		if (bus == null)
			return new ModelAndView("redirect:/jsp/index.jsp");
		int busid = bus.getBusinessId();
		String refno = request.getParameter("refno");
		logger.info("the reference number is" + refno);
		
		//OpportunityDAO oprDAO = new OpportunityDAO();

		CurrencyDAO curDAO=new CurrencyDAO();
		Currency cur=curDAO.getCurrncy(busid);
		float dollar=cur.getDollar();
		Opportunity opp=OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(),refno.trim());
		Clientdet clientdet=null;
		clientdet=opp.getClientId();
		clientdet.setDivision(opp.getDivision());
		int rid=opp.getId();
		String curr=opp.getCurencytype();
    List<NewQuotVO> quotlist=new ArrayList<NewQuotVO>();
   
	SourceInfoDAO sDAO=new SourceInfoDAO();
	PartsDAO partsDAO=new PartsDAO();
		List<Parts> partlst = partsDAO.getParts(refno.trim(),
				bus.getBusinessId());
		SupplierDAO supDAO = new SupplierDAO();
		SourcesDAO srDAO = new SourcesDAO();
		//Opportunity op = oprDAO.findById(rid, bus.getBusinessId());
		Currency cr = null;
		try {
			cr = curDAO.getCurrncy(bus.getBusinessId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		SourceInfoDAO siDAO = new SourceInfoDAO();
		
		for (Parts p : partlst) {
			NewQuotVO newquot = new NewQuotVO();
			int i = 1;
			String s = p.getPrtnum();
			if (s.length() == 0) {
				s = p.getDescription();
			}
			newquot.setPartId(p.getPartid());
			newquot.setQuotid(i);

			newquot.setDescription(p.getDescription());
			logger.info("th description" + p.getDescription());
			
			
			logger.info("th description" + p.getMake());
			newquot.setMake(p.getMake());
			int pr = p.getPartid();
			Sourcecompare sco = sDAO.getCmprId(rid, pr, bus.getBusinessId());
			String srname = "";
			String spname = "";
			if (s.equalsIgnoreCase(sco.getOfferingPartNo())) {
				newquot.setPartNo(s);
			} else {
				newquot.setPartNo(s + "(" + sco.getOfferingPartNo() + ")");
			}
			float unitprice = 0;
			if (sco != null) {
				int srnum = sco.getSrcnum();
				srname = srDAO.findById(srnum, bus.getBusinessId())
						.getSourceName();
				logger.info("the sourcename is" + srname);
				int spnum = sco.getSupplier();
				if (spnum > 0) {
					spname = supDAO.findById(spnum, bus.getBusinessId()).getName();
					logger.info("the suppliername  is" + spname);
				}
				newquot.setSourceName(srname);
				newquot.setSuppName(spname);
				
				SourceInfo si = siDAO.getSrInfo(rid, pr, srnum, spnum,
						bus.getBusinessId());
				String currency = si.getCurrency();
				newquot.setReqQty(si.getMoq());
				float crval = 0;
				if (cr != null) {
					if (currency.equalsIgnoreCase(Constants.ST_CUR_DOLLAR)) {
						crval = cr.getDollar();
					} else if (currency.equalsIgnoreCase(Constants.ST_CUR_EURO)) {
						crval = cr.getEuro();
					} else if (currency.equalsIgnoreCase(Constants.ST_CUR_POUND)) {
						crval = cr.getPound();
					} else if (currency.equalsIgnoreCase(Constants.ST_CUR_RUPEE)) {
						crval = 1;
					} else if (currency.equalsIgnoreCase(Constants.ST_CUR_SDOLLAR)) {
						crval = cr.getSdollar();
					} else if (currency.equalsIgnoreCase(Constants.ST_CUR_YEN)) {
						crval = cr.getYen();
					}
				}
				unitprice = sco.getUnitprice();
				newquot.setCurrency(crval);
				newquot.setUnitprice(unitprice);
			}
			i++;
			quotlist.add(newquot);
		}
		String shName = bus.getShortname();
		Business comp = bus;
		logger.info("comany name " + comp);
		String terms = request.getParameter("termsAndConditions");

		logger.info("terms and conditions " + terms);
		if(curr.equals(Constants.ST_CUR_DOLLAR)){
			model = new ModelAndView("/jsp/NewQuotationDollarRes.jsp");
		}else{
			model = new ModelAndView("/jsp/NewQuotationRes.jsp");
		}
		
		model.addObject("tnc", terms);

		model.addObject("newquotlist", quotlist);

		QuotationDAO quDAO = new QuotationDAO();
		List<Quotation> listquot = quDAO.getQuotCount(rid, bus.getBusinessId());
		model.addObject("listquot", listquot);

		Quotation quotObj = new Quotation();

		ClientdetDAO cliDAO = new ClientdetDAO();
		String orgname = opp.getOrganisation();
		Clientdet cli = cliDAO.getCliOrg(bus.getBusinessId(), orgname);
		String cl = cli.getShrtname();
		String clShName = cl;

		quotObj.setClientid(cli);

		quotObj.setOrdrby(shName);
		String div = opp.getDivision();
		String enqType = opp.getEnquirytype();

		java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
		String d = date.toString();
		quotObj.setQutdate(d);

		java.sql.Date da=opp.getDuedate();
		SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
		String quotDate=sdf.format(da);
		QuotationDAO qDAO = new QuotationDAO();
		int serialno = listquot.size();
		long qutnum = qDAO.getqutid(enqType, bus.getBusinessId());
		logger.info("the serial no is" + serialno);
		String qutid = "";
		/*if (enqType.equals("TE") || enqType.equals("CP") || enqType.equals("PE")|| enqType.equals("OPTS")) {*/
			StringBuilder sb = null;
			/*if (qutnum == 1) {*/
				sb = new StringBuilder();
				sb.append(shName+"/"+clShName+"/"+div+"/"+enqType+"/"+qutnum);
				if (serialno != 0) {
					sb.append("{" + serialno + "}");
				}
				sb.append("/").append(quotDate);
				qutid = sb.toString();
			/*} else {
				sb = new StringBuilder();
				sb.append(shName+"/"+clShName+"/"+div+"/"+enqType+"/"+qutnum);
				if (serialno != 0) {
					sb.append("{" + serialno + "}");
				}
				sb.append("/"+quotDate);
				qutid = sb.toString();
			}*/
			
		/*}*/
		quotObj.setQuotno(qutid);
		/*if (enqType.equals("BQ")) {
			StringBuilder sb = null;
			if (qutnum == 1) {
				sb = new StringBuilder();
				sb.append(shName).append("/").append(clShName).append("/");
				sb.append(div).append("/").append(enqType).append("/")
						.append(qutnum);
				if (serialno != 0) {
					sb.append("{" + serialno + "}");
				}
				sb.append("/").append(quotDate);
				qutid = sb.toString();

			} else {
				sb = new StringBuilder();
				sb.append(shName).append("/").append(clShName).append("/");
				sb.append(div).append("/").append(enqType).append("/")
						.append(qutnum);
				if (serialno != 0) {
					sb.append("{" + serialno + "}");
				}
				sb.append("/").append(quotDate);
				qutid = sb.toString();
			}
		}*/
		VariablesDAO v = new VariablesDAO();
		Variables variables = v.getVariables(busid);
		Currency currency = curDAO.getCurrncy(busid);
		model.addObject("genQuotNo", qutid)
		.addObject("dollarValue", dollar)
		.addObject("business", bus)
		.addObject("variables", variables)
		.addObject("enqCurrType", curr)
		.addObject("opportunity", opp)
		.addObject("currency", currency);
		model.addObject("client",clientdet)	;
		model.addObject("user",opp.getUser())	;
		return model;
	}

	@RequestMapping(value = "/get_history.do", method = RequestMethod.GET)
	public String htmlReport(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Business bus = (Business) session.getAttribute("business");

		String quotno = request.getParameter("quotid");
		AttachmentHistoryDAO atDAO = new AttachmentHistoryDAO();
		AttachmentHistory att = atDAO.getAttachmentHistoryByRefno(
				bus.getBusinessId(), Constants.QUOTATION, quotno.trim());
		logger.info("the quotation no is " + quotno.trim());
		byte[] pdfReport = att.getFileBlob();
		logger.info("the length of pdf is" + pdfReport.length);
		ServletOutputStream servletOutputStream = response.getOutputStream();
		response.setContentType("application/msword");
		String fileName = "quotation.doc";
		response.setHeader("Content-Disposition", "inline; filename=" + fileName);
		response.setContentLength(pdfReport.length);
		servletOutputStream.write(pdfReport);
		servletOutputStream.flush();
		servletOutputStream.close();
		return null;

	}

	@RequestMapping("/get_techbid.do")
	public String getTechnicalbid(HttpSession session,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Business bus = (Business) session.getAttribute("business");

		String quotno = request.getParameter("quotid");
		AttachmentHistoryDAO atDAO = new AttachmentHistoryDAO();

		AttachmentHistory att = atDAO.getAttachmentHistoryByRefno(
				bus.getBusinessId(), Constants.TECHNICAL_QUOTATION, quotno.trim());
		System.out.println("the quotation no is " + quotno.trim());
		System.out.println("the business id is  " + bus.getBusinessId());
		byte[] pdfReport = att.getFileBlob();
		System.out.println("the length of pdf is" + pdfReport.length);
		ServletOutputStream servletOutputStream = response.getOutputStream();
		response.setContentType("application/msword");
		response.setContentLength(pdfReport.length);
		servletOutputStream.write(pdfReport);
		servletOutputStream.flush();
		servletOutputStream.close();
		return null;

	}

	@RequestMapping("/closeQuot.do")
	public ModelAndView closeQuot(HttpServletRequest request,
			HttpSession session, ModelAndView model) throws Exception {
		Business bus = (Business) session.getAttribute("business");
		if (bus == null)
			return new ModelAndView("redirect:/jsp/index.jsp");
		String quotid = request.getParameter("quotid");
		String closedesc = request.getParameter("desc");
		QuotationDAO quotDAO = new QuotationDAO();
		int id = Integer.parseInt(quotid);
		Quotation quot = quotDAO.getByid(id);
		quot.setClosedesc(closedesc);
		quot.setRemarks("closed");
		quotDAO.insert(quot);
		
		QuotPartsDAO qpDAO = new QuotPartsDAO();
		List<QuotParts> lqpObj=new ArrayList<QuotParts>();

		String rcount = request.getParameter("rowcount");
		int rowcount = Integer.parseInt(rcount);
		for (int i = 1; i <= rowcount; i++) {
			String cprice = request.getParameter("cprice" + i);
			String other = request.getParameter("other" + i);
			String partsrid = request.getParameter("id" + i);
			int psid = Integer.parseInt(partsrid);

			

			QuotParts qpObj = qpDAO.findQPbyId(psid, bus.getBusinessId());
			System.out.println("the qpObj is" + qpObj);

			qpObj.setOtherparty(cprice);
			qpObj.setOther(other);
			lqpObj.add(qpObj);
		}// end of for looop
		qpDAO.insertList(lqpObj);
		return new ModelAndView("/jsp/closeQuotMsg.jsp")
				.addObject("submenu", "reports")
				.addObject("menuName", "reports")
				.addObject("oprtobj",quot.getEnqid());

	}
	@RequestMapping("/QuotToEnq.do")
	public ModelAndView QuotToEnq(HttpServletRequest request,
			HttpSession session, ModelAndView model) throws Exception {
		Business bus = (Business) session.getAttribute("business");
		if (bus == null)
			return new ModelAndView("redirect:/jsp/index.jsp");
		String refid = request.getParameter("refnoId");
		//OpportunityDAO oprDAO=new OpportunityDAO();
	   int 	rid=Integer.parseInt(refid);
		Opportunity op = OpportunityDAO.getSingleInstance().findById(rid, bus.getBusinessId());
		op.setRemarks("Converted To New Enquiery After Quotation");
		OpportunityDAO.getSingleInstance().insert(op);
		PartsDAO prtdao=new PartsDAO();
		List<Parts> prt= prtdao.getPartsByIds(bus.getBusinessId(),rid);
	ClientdetDAO cliDAO=new ClientdetDAO();
		
		List<Clientdet> orgList=new ArrayList<Clientdet>();
		try {
			orgList=cliDAO.getorg(bus.getBusinessId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		ExecutivesDAO edao=new ExecutivesDAO();
		List<Executives> le=edao.findAll(bus.getBusinessId());
		return new ModelAndView("/jsp/QuotToEnq.jsp")
				.addObject("submenu", "enquiry")
				.addObject("menuName", "enquiry")
				.addObject("oprtobj",op)
				.addObject("partslst",prt)
				.addObject("compList",bus)
				.addObject("executives",le)
				.addObject("orgList",orgList);

	}
}
